const {
  createDictionary,
  getAllDictionary,
  updateDictionary,
  deleteDictionary,
} = require("../../service//common/dictionary.service");
const {
  addError,
  queryError,
  updateError,
  DataDoesNotExist,
} = require("../../constant/err.type");

const {
  querySuccess,
  addSuccess,
  updateSuccess,
  deleteSuccess,
} = require("../../constant/success.type");

class DictionaryController {
  async addDictionary(ctx, nuxt) {
    try {
      ctx.verifyParams({
        title: { type: "string", required: true },
        type: { type: "string", required: true },
        code: { type: "number", required: true },
      });
      const { id } = ctx.state.user;
      ctx.request.body.added_by = id;
      try {
        const db_response = await createDictionary(ctx.request.body);
        ctx.body = addSuccess;
      } catch (err) {
        addError.result = err;
        return ctx.app.emit("error", addError, ctx);
      }
    } catch (err) {
      addError.result = err;
      ctx.body = addError;
    }
  }
  async getDictionary(ctx, nuxt) {
    try {
      const db_response = await getAllDictionary(ctx.request.query);
      querySuccess.result = db_response;
      ctx.body = querySuccess;
    } catch (err) {
      console.log(err);
      ctx.app.emit("error", queryError, ctx);
    }
  }
  async updateDictionary(ctx, nuxt) {
    try {
      ctx.verifyParams({
        id: { type: "string", required: true },
        title: { type: "string", required: true },
        type: { type: "string", required: true },
        code: { type: "number", required: true },
      });
      try {
        const db_response = await updateDictionary(ctx.request.body);
        if (db_response) {
          ctx.body = updateSuccess;
        } else {
          ctx.body = DataDoesNotExist;
        }
      } catch (err) {
        updateError.result = err;
      }
    } catch (err) {
      updateError.result = err;
      return ctx.app.emit("error", updateError, ctx);
    }
  }
  async deleteDictionary(ctx, nuxt) {
    try {
      const db_response = await deleteDictionary(ctx.request.query.id);
      if (db_response) {
        ctx.body = deleteSuccess;
      } else {
        ctx.body = DataDoesNotExist;
      }
    } catch (err) {
      updateError.result = err;
    }
  }
}

module.exports = new DictionaryController();
